package ca.paulshin.yunatube.services;

import static ca.paulshin.yunatube.database.YuNaTubeSqliteDatabase.getInstance;

import java.util.List;

import android.app.IntentService;
import android.content.Intent;
import android.util.Pair;
import ca.paulshin.yunatube.YunaTubeApplication;
import ca.paulshin.yunatube.common.Persistent;
import ca.paulshin.yunatube.common.Preference;
import ca.paulshin.yunatube.common.Utils;
import ca.paulshin.yunatube.http.FlickrDataLoader;
import ca.paulshin.yunatube.http.YouTubeDataLoader;
import ca.paulshin.yunatube.main.MainActivity;
import ca.paulshin.yunatube.services.broadcast.DownloadReceiver;

public class DownloadService extends IntentService {
	private static final String XML_VERSION = "xml_version";
	public static final String NOTICE_KEY = "notice_key";
	public static final String FACT_KEY = "fact_key";
	public static final String TODAY_PHOTO_KEY = "today_photo_key";

	public static final String EXTRA_LATEST_XML_VERSION = "latest_xml_version";

	public DownloadService() {
		super(DownloadService.class.getName());
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		// Load notices
		List<String> notices = YouTubeDataLoader.getLoaderInstance().loadNotices();
		
		// Load fact
		if (Utils.isAppLocaleKorean()) {
			Pair<String, String> pair = YouTubeDataLoader.getLoaderInstance().loadFact();
			Persistent.put(FACT_KEY, pair.first);
			Persistent.put(TODAY_PHOTO_KEY, pair.second);
		}
		
		int latestXMLVersion = Integer.parseInt(notices.remove(0));
		int currentXMLVersion = Preference.get(XML_VERSION, 0);
		
		int index = 0;
		Persistent.remove(NOTICE_KEY, null);
		for (String notice : notices) {
			Persistent.put(NOTICE_KEY, String.valueOf(index++), notice);
		}
		
		if (latestXMLVersion > currentXMLVersion || Preference.getBoolean(MainActivity.IS_LOCALE_CHANGED)) {
			// Update needed
			getInstance().removeAll();
			Utils.debug("Database tables are cleared");
			
			// Load XML
			YouTubeDataLoader loader = YouTubeDataLoader.getLoaderInstance();
			boolean isSuccessful = loader.loadXML();
			
			if (isSuccessful) {
				Intent finishIntent = new Intent();
				finishIntent.setAction(DownloadReceiver.ACTION);
				
				Preference.put(XML_VERSION, latestXMLVersion);
				Preference.put(MainActivity.IS_LOCALE_CHANGED, false);
				
				finishIntent.putExtra(EXTRA_LATEST_XML_VERSION, latestXMLVersion);
				YunaTubeApplication.broadcast.sendBroadcast(finishIntent);
			}
		}
		else {
			// Update MainContent view(notices, fact)
			Intent finishIntent = new Intent();
			finishIntent.setAction(DownloadReceiver.ACTION);
			
			finishIntent.putExtra(EXTRA_LATEST_XML_VERSION, latestXMLVersion);
			YunaTubeApplication.broadcast.sendBroadcast(finishIntent);
		}
		
		// Load Flickr
		YunaTubeApplication application = (YunaTubeApplication) Utils.ctx;
		application.collectionList = FlickrDataLoader.getInstance().getCollectionList();
	}
}
